#include <stdio.h>
#include <stdlib.h>

void print_backtrace() {
  char cmd[256];
  unsigned long *fp;
  unsigned long *pc, *current_pc;
  //fp = __builtin_frame_address(0);
  asm("mov $fp, %0":"=r"(fp));
  asm("br %0, 0":"=r"(current_pc));
  printf("--------------stack backtrace---------------\n");
  snprintf(cmd, sizeof(cmd), "echo -n \"[#0] %p \" && addr2line -fpCse ./fp_backtrace %p", current_pc, current_pc);
  system(cmd);
  for (int i=1; i<5; i++) {
    pc = (unsigned long *) fp[0];
    fp = (unsigned long *) fp[1];
    snprintf(cmd, sizeof(cmd), "echo -n \"[#%d] %p \" && addr2line -fpCse ./fp_backtrace %p", i, pc, pc);
    system(cmd);
  }
  printf("--------------------------------------------\n");
}

void func3()
{
  print_backtrace();
}

void func2()
{
  func3();
}

void func1()
{
  func2();
}

int main()
{
  func1();
}
